import React, { useEffect, useState, useCallback, } from 'react';
import { Table, Divider, Modal, Form, Input, Select, Switch, Row, Col, Button, message, Popconfirm } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import MenuTree from '@/components/MenuTree';
import SearchBox from '@/components/SearchBox'
import { fetchRoleList } from '@/services/role';
import {
  fetchUserList,
  deleteUser,
  saveOrUpdateUser,
  assignMutipleRoles,
  assignRole,
  getRolesByUserId,
} from '@/services/merchants';
import { 
  changePassword,
} from '@/services/login'
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils'

const { confirm } = Modal;
const { Option } = Select;
const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
console.log('1', hasSearchBtn);

const columns = [
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    key: 'nickname',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: text => <span>{text == 0 ? '启用' : '锁定'}</span>,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
];

const Role = props => {
  const { getFieldDecorator } = props.form;
  const { inform } = props.role;
  const [data, setColData] = useState([]);
  const [role, setRoleData] = useState([]);
  const [ownRoles, setOwnRoles] = useState([])
  const [password, setPassword] = useState('')
  const [confirmPsd, setConfirmPsd] = useState('')
  const [record, setRecord] = useState({})
  const [btnType, setBtnType] = useState('')
  // 编辑\新增模态框
  const [isShow, setState] = useState(false);
  // 权限模态框
  const [visible, setVisible] = useState(false);
  // 分配角色模态框
  const [showed, setShowed] = useState(false);
  // 角色id
  const [roleId, setRoleId] = useState([])
  
  useEffect(() => {
    getList();
    getRoles()
  }, []);

  // 用户列表
  const getList = useCallback(async params => {
    const r = await fetchUserList(params);
    setColData(r.data);
  }, []);

  // 新增修改用户
  const handleUser = useCallback(async params => {
    const r = await saveOrUpdateUser(params);
    if (r.code == 0) getList();
  }, []);

  // 角色列表数据
  const getRoles = useCallback(async () => {
    const roles = await fetchRoleList();
    setRoleData(roles.data);
  }, []);

  const removeUser = useCallback(async record => {
    const res = await deleteUser({
      id: record.id,
    });
    if (res.code == 0) {
      const index = data.findIndex(e => e.id == record.id);
      setColData(() => {
        data.splice(index, 1);
        return [...data];
      });
    }
  }, [data]);

  const getOwnRoles = useCallback(async id => {
    const res = await getRolesByUserId(id)
    const lists = []
    res.data.map(e => lists.push(e.id))
    setOwnRoles(lists)
  }, [])

  const fetchChangePsw = useCallback(async params => {
    const res = await changePassword(params)
    res.code == 0 && message.success('修改成功')
  }, [])

  // 新增/修改模态框
  const handleStatus = useCallback(record => {
    setState(!isShow);
    props.dispatch({
      type: 'role/changeModelState',
      payload: {
        inform: record,
      },
    });
  }, [isShow]);

  // 分配角色模态框
  const assignStatus = useCallback(record => {   
    getOwnRoles({
      sys_user_id: record.id
    }).then(() => setVisible(!visible))

    props.dispatch({
      type: 'role/changeModelState',
      payload: {
        inform: record,
      },
    });
  }, []);

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        const params = {
          ...inform,
          ...values,
          status: !!values.status ? 0 : 1,
        }
        btnType != 1 && Object.assign(params, {id: values.id ? values.id : inform.id})

        handleUser(params)
        setState(!isShow);
      }
    });
  };

  // 分配角色逻辑
  const submitRoles = () => {
    assignMutipleRoles({
      sysUserId: inform.id,
      sysRoleIds: roleId,
    })
    setVisible(!visible);
  };

  // 选择角色
  const selectRoles = value => setRoleId(value)

  // 查询表单
  const getFields = () => {
    return (
      <Col span={8}>
        <Form.Item label={`用户名`}>
          {getFieldDecorator(`getusername`, {})(<Input />)}
        </Form.Item>
      </Col>
    );
  };
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      console.log('Received values of form: ', values);
      getList({
        ...values,
        username: values.getusername,
      });
    });
  };

  // 清空查询条件
  const handleReset = () => {
    props.form.resetFields();
    getList()
  };

  // 按钮逻辑
  const handleBtn = type => {
    setBtnType(type)
    if (record.length != 1 && type != 1) return message.warning('请选择一个用户！');
    switch (type) {
      // 新增
      case 1:    
        return handleStatus();
      case 3:      
        return handleStatus(record[0]);
      // 查询
      case 2:      
        return handleSearch();
      // 删除
      case 4:
        return removeUser(record[0])
      // 授权
      case 6:
        return assignStatus(record[0])
      // 修改密码
      case 7:
        return changePsw()
      default:
        break;
    }
  };

  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setRecord(selectedRows)
    },
  };
  
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowSelection={rowSelection}
        rowKey={record => record.id}
      />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="用户名">
            {getFieldDecorator('username', {
              initialValue: inform && inform.username,
              rules: [
                {
                  required: true,
                  message: '请输入至少长度为5的用户名',
                  min: 5,
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="昵称">
            {getFieldDecorator('nickname', {
              initialValue: inform && inform.nickname,
              rules: [
                {
                  required: true,
                  message: '请输入昵称',
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="密码">
            {getFieldDecorator('password', {
              initialValue: inform && inform.password,
              rules: [
                {
                  required: true,
                  message: '请输入密码',
                },
              ],
            })(<Input type="password" onChange={e => setPassword(e.target.value)} />)}
          </Form.Item>
          {/* 新增时再次确认密码 */}
          {
            !inform && <Form.Item label="确认密码" hasFeedback validateStatus={password == confirmPsd ? "success" : "error"}>
              {getFieldDecorator('confirmPsd', {
                rules: [
                  {
                    required: true,
                    validator(rule, value, callback) {                      
                      if (password != value) callback('两次输入不一致！')
                      callback()
                    }
                  },
                ],
              })(<Input 
                  type="password" 
                  onChange={e => setConfirmPsd(e.target.value)} 
                />)}
            </Form.Item>
          }
          <Form.Item label="状态">
            {getFieldDecorator('status', {
              initialValue: inform && !inform.status ? true : false,
              valuePropName: 'checked',
            })(<Switch />)}
          </Form.Item>
        </Form>
      </Modal>
      {/* 分配角色 */}
      <Modal
        title="分配角色"
        visible={visible}
        onOk={submitRoles.bind(this)}
        onCancel={() => setVisible(!visible)}
        destroyOnClose
      >
        角色：<Select 
          showSearch 
          mode="multiple" 
          onChange={selectRoles} 
          style={{ width: 200 }}
          defaultValue={ownRoles}
        >
          {role.map(e => (
            <Option value={e.id} key={e.id}>{e.name}</Option>
          ))}
        </Select>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(Role));
